<template>
	<view class="page-content flex-col">
		<!-- 聊天列表 -->
		<scroll-view id="scrollview" scroll-y :scroll-with-animation="true" :scroll-into-view="scrollIntoView"
			:refresher-enabled="true" @refresherrefresh="handlerefresh" :refresher-triggered="showrefresh"
			style="flex: 1; overflow: hidden">
			<view class="list">
				<block v-for="(item,index) in list" :key="index">
					<user-chat-list :item="item" :index="index"></user-chat-list>
				</block>
				<!-- 用于定位到底部 -->
				<view id="last-msg-item" style="height: 1px;"></view>
			</view>
		</scroll-view>

		<!-- 输入框 -->
		<view class="send-box">
			<userChatBottom @submit="submit"></userChatBottom>
		</view>
	</view>
</template>

<script>
	import userChatBottom from "components/user-chat/user-chat-bottom";
	import userChatList from "components/user-chat/user-chat-list";
	import mine from "../../../api/mine.js";
	import utils from "../../../utils/util.js";
	export default {
		data() {
			return {
				list: [],
				style: {
					contentH: 0,
					itemH: 0
				},
				receiverPhoto: '',
				receiverId: '',
				scrollIntoView: '',
				socketOpen: false, //是否连接
				path:'ws://37339q7s12.qicp.vip/websocket/',//"wss://petspacket.com/ws/websocket/"
				socket: "",
				sendPhoto: '',
				filterParams: {
					pageNum: 0,
					pageSize: this.$config.pageSize,
				},
				status: 'loadmore',
				showrefresh: false,
			}
		},
		components: {
			userChatBottom,
			userChatList
		},
		onLoad(option) {
			const userinfo = uni.getStorageSync('userinfo');
			if (userinfo) {
				this.path += userinfo.id;
				this.sendPhoto = userinfo.avatar.split(',')[0]
			}
			if (option.userId && option.userId != 'undefined') {
				this.getUserInfo(option.userId);
				this.receiverId = option.userId;
			}
			this.sokcet();
		},
		methods: {
			scrollToBottom() {
				this.$nextTick(() => {
					this.scrollIntoView = "last-msg-item"
					// 清空，为下一次定位做准备
					this.$nextTick(() => {
						this.scrollIntoView = ""
					})
				})
			},
			//获取聊天数据
			getdata(toUserId) {
				// console.log(toUserId, this.status);
				if (this.status === 'loadmore') {
					this.status = "loading";
					this.filterParams.pageNum++;
					mine.getMessageHistoryList(toUserId, this.filterParams).then(res => {
						console.log("res", res);
						if (res.code == 200) {
							if (res.rows?.length < this.$config.pageSize)
								this.status = "nomore";
							else {
								this.status = "loadmore";
							}
							const userinfo = uni.getStorageSync('userinfo');
							const transData = res.rows.map(item => {
								item.isme = false;
								item.sendError = false;
								item.createTime = utils.formatMessageDate(item.createTime);
								if (userinfo.id == item.sendId) {
									item.isme = true;
									item.avatar = this.sendPhoto;
								} else {
									item.avatar = this.receiverPhoto
								}
								if (item.isPicture == 2) {
									const location = JSON.parse(item.content)
									const covers = [{
										latitude: location.lat,
										longitude: location.lng,
										iconPath: '/static/common/location-end.png',
										width: 10,
										height: 10
									}];
									item.content = location;
									item.covers = covers;
								}
								return item;
							});
							this.list.unshift(...transData);
							this.showrefresh = false;
							if (this.filterParams.pageNum === 1) {
								this.scrollToBottom()
							}
						}
					}).catch((err) => {
						this.status = "nomore";
						this.showrefresh = false;
						console.log(err);
					});
				}
			},
			submit(msg) {
				//发布
				const now = new Date();
				let obj = {
					isme: true,
					avatar: this.sendPhoto,
					isPicture: msg.isPicture,
					createTime: utils.formatMessageDate(now),
					content: msg.content,
					sendError: false,
				}
				console.log(msg);
				if (msg.isPicture == 1) {
					if (msg.content) {
						obj.content = msg.content;
					} else {
						obj.content = msg.tempUrl;
						obj.sendError = true;
					}
				} else if (msg.isPicture == 2) {
					const location = JSON.parse(msg.content)
					const covers = [{
						latitude: location.lat,
						longitude: location.lng,
						iconPath: '/static/common/location-end.png',
						width: 10,
						height: 10
					}];
					obj.content = JSON.stringify(location);
					obj.covers = covers;
				}
				this.list.push(obj);
				this.scrollToBottom();
				if (this.socketOpen == false || obj.sendError) {
					return
				}
				console.log(obj);
				try {
					//通过 WebSocket 连接发送数据
					let str = JSON.stringify({
						message: obj.content,
						isPicture: obj.isPicture,
						toUser: this.receiverId,
						type: 1
					})
					uni.sendSocketMessage({
						data: str
					});
				} catch (e) {
					console.log(e, '断线啦')
					uni.closeSocket();
				}
			},

			//建立链接
			sokcet() {
				var that = this;
				uni.closeSocket();
				this.socketOpen = false;
				try {
					//WebSocket的地址
					const url = this.path;
					// 连接
					uni.connectSocket({
						url: url,
					});
					// 监听WebSocket连接已打开
					uni.onSocketOpen(function(res) {
						console.log(res, 'WebSocket连接已打开！');
						that.socketOpen = true;
					});
					// 监听连接失败
					uni.onSocketError(function(err) {
						console.log('WebSocket连接打开失败，请检查！', err);
						// e.code === 1000  表示正常关闭。 无论为何目的而创建, 该链接都已成功完成任务。
						// e.code !== 1000  表示非正常关闭。
						if (err && err.code !== 1000) {
							setTimeout(function() {
								that.socketOpen = true;
								uni.connectSocket({
									url: url,
								});
							}, 5 * 1000)
						}
					});
					// 监听连接关闭
					uni.onSocketClose(function(err) {
						console.log('WebSocket连接关闭！', err);
						if (err && err.code !== 1000) {
							setTimeout(function() {
								that.socketOpen = true;
								uni.connectSocket({
									url: url,
								});
							}, 5 * 1000)
						}
					});
					// 监听收到信息
					uni.onSocketMessage((res) => {
						console.log(res, 'WebSocket监听收到信息！', res);
						const now = new Date();
						uni.hideLoading()
						//与后端规定好返回值分别代表什么，写业务逻辑
						// JSON.parse()
						const serverData = JSON.parse(res.data); //这是字符串，如果要对象记得转换一下
						let obj = {
							isme: false,
							avatar: this.receiverPhoto,
							isPicture: serverData.isPicture,
							createTime: utils.formatMessageDate(now),
							content: serverData.message,
							sendError: false,
						}
						if (serverData.isPicture == 2) {
							const location = JSON.parse(serverData.message)
							const covers = [{
								latitude: location.lat,
								longitude: location.lng,
								iconPath: '/static/common/location-end.png',
								width: 10,
								height: 10
							}];
							obj.content = location;
							obj.covers = covers;
						}
						this.list.push(obj);
						this.scrollToBottom();
					})
				} catch (e) {
					console.log(e)
				}
			},
			getUserInfo(userid) {
				mine.getUserInfo(userid).then(res => {
					if (res.code == 200) {
						const formdata = res.data;
						uni.setNavigationBarTitle({
						        title: res.data.nickName,
										});
						if (
							formdata.avatar !== null &&
							formdata.avatar !== undefined &&
							formdata.avatar
						) {
							this.receiverPhoto = formdata.avatar.split(",")[0];
						} else {
							this.receiverPhoto = "";
						}
						this.getdata(userid)
					}
				}).catch(err => {
					this.getdata(userid)
				})
			},
			handlerefresh() {
				this.showrefresh = true;
				this.getdata(this.receiverId)
			}
		},
		//监听页面卸载
		onUnload() {
			console.log('退出页面')
			if (this.socketOpen == true) {
				uni.closeSocket();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page-content {
		height: 100%;
		width: 100%;
		background-color: #FFFFFF;

		.list {
			padding: 32rpx;
			box-sizing: border-box;
		}

		.send-box {
			background: #FFFFFF;
			box-shadow: 0rpx -8rpx 30rpx 0rpx rgba(0, 0, 0, 0.05);
			padding: 16rpx;
			height: max-content;
			padding-bottom: 32rpx;
		}
	}
</style>